angular.module('Controller')

.controller('WIRaspberryManageCtrl', ($scope, NgTableParams, menuManage, commonUtil, commonConstant, $rootScope, $uibModal, $http) ->
  initSearchData = ()->
    $scope.search = {
      enabled: true
    }
  initSearchData()

  $scope.sexList = commonConstant.sexList(true)
  $scope.enabledList = commonConstant.enabledList(true)
  $scope.tableParams = new NgTableParams(
    {page: 1, count: commonConstant.pageTableCount},
    {
      counts: [5, 10, 20],
      getData: ($defer, params)->
        $scope.doQuery($defer, params)
        return;
#                    params.total($scope.tableData.length)
#                    $defer.resolve($scope.tableData.slice((params.page() - 1) * params.count(), params.page() * params.count()))
    }
  )


  $scope.doQuery = ($defer, params)->
    requestData = {
      page: params.page() - 1,
      size: params.count(),
      usernameLike: $scope.search.name
    }
    getParam = commonUtil.transferGetParam(requestData)
    $http.get('@ostengar/raspberryPi' + getParam)
    .success (resp)->
      if resp.code == 0
        $scope.tableData = resp.message.content
        params.total(resp.message.totalElements)
        $defer.resolve($scope.tableData)
      else
        console.log(resp.message)
    .error (err)->
      console.log(err)


  _.extend $scope,
    newData: ->
#            $rootScope.pageParams={name:'',sex:true,enabled:1}
#            $rootScope.pageType='new'
#            menuManage.goState('account-manage-edit',true)
      data = {name: '', sex: true, enabled: 1}
      showModal('new', data)
    editData: (data)->
      $rootScope.pageParams = angular.copy(data)
      $rootScope.pageType = 'edit'
      menuManage.goState('wi-raspberry-edit', true)

    resetSearch: ->
      initSearchData()
    queryData: (firstPage)->
      if(firstPage == true)
        $scope.tableParams.page(1)
      $scope.tableParams.reload()
    printData: (item)->
      $scope.printItem = {
        name: item.name
        uuid: item.uuid
        time: moment().format('YYYY-MM-DD hh:mm:ss')
        img: $("[data=T#{item.uuid}]").children("a:first-child").attr('href')
      };
      _.defer(()->
        $("#item-print-container").jqprint();
        $scope.printItem = undefined
      )
      ''
  showModal = (type, data)->
    $scope.modal = $uibModal.open({
      animation: true,
      appendTo: $("#modalContent:eq(0)"),
      controller: 'WIRaspberryManageNewCtrl',
      templateUrl: 'templates/wi/raspberry/raspberry-manage-modal.html',
      resolve: {
        items: ()-> {type: type, data: data}
      }
    })
  $scope.modal.result.then((modalData)->
    $scope.queryData()
  )
)
